package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.EnrollDetail;
import com.xmy.cultivate.entity.views.EnrollGrantCount;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 招生数据 服务实现类
 * </p>
 *
 * @author min
 * @since 2023-02-10
 */
@Service
public class EnrollInfoServiceImpl extends ServiceImpl<EnrollInfoMapper, EnrollInfo> implements IEnrollInfoService {

    @Autowired
    EnrollInfoMapper enrollInfoMapper;

    @Autowired
    StaffMapper staffMapper;

    @Autowired
    @Lazy
    OrderApplyMapper orderApplyMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    IEnrollTeamMemberService iEnrollTeamMemberService;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    SubjectsMapper subjectsMapper;

    @Autowired
    @Lazy
    OrganizationMapper organizationMapper;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    IRecordCourseService iRecordCourseService;

    @Autowired
            @Lazy
    IEnrollInfoGrantSchoolService iEnrollInfoGrantSchoolService;
    @Autowired
    private RecordCourseMapper recordCourseMapper;


    public List<EnrollInfo> getEnrollInfoList(String orderId){
        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.eq("order_id",orderId);
        enrollInfoQueryWrapper.orderByAsc("type");
        List<EnrollInfo> enrollInfoList = enrollInfoMapper.selectList(enrollInfoQueryWrapper);

        for (EnrollInfo enrollInfo:enrollInfoList){
            Staff staff = staffMapper.selectById(enrollInfo.getTeacherId());
            if(staff != null){
                enrollInfo.setTeacherName(staff.getName());
            }
        }
        return enrollInfoList;
    }

    public boolean addEnrollInfo(OrderApply orderApplyInfo){

        OrderApply orderApply = orderApplyMapper.selectById(orderApplyInfo.getId());
        if(orderApply == null){
            throw new CommonException(ResultCode.NOORDER);
        }
        OrderDetail orderDetail = orderDetailMapper.selectOne(new QueryWrapper<OrderDetail>().eq("order_id",orderApply.getId()).last("limit 1"));


        BigDecimal inviteMoney = new BigDecimal(120);
        BigDecimal auditionMoney = new BigDecimal(40);
        BigDecimal bargainMoney = new BigDecimal(40);
        LocalDate localDate = LocalDate.now();

        //邀约:1
        if(orderApplyInfo.getInviteList()!=null){
            Integer inviteCount = orderApplyInfo.getInviteList().size();
            if(inviteCount>0){
                Long inviteCountAt = this.getEnrollInfoCount(orderApply.getId(),1);

                Double dealNum = 1.0/inviteCount;
                Integer i = 0;
                Integer type = 1;
                for (Long id:orderApplyInfo.getInviteList()){
                    if((i+inviteCountAt)<2){
                        Long teamId =  iEnrollTeamMemberService.getTeamIdForteacherId(id);
                        addEnrollInfoType(id,teamId,orderDetail.getSubjectsId(),orderApply.getStudentId(),orderApply.getId(),orderApply.getSchoolId(),dealNum,inviteMoney,inviteCount,orderApply.getHandleDate(),type);
                    }
                    i++;
                }
                this.updateEnrollDeal(orderApply.getId(),1);
            }
        }

        if(orderApplyInfo.getAuditionList() !=null){
            //试听:2
            Integer auditionCount = orderApplyInfo.getAuditionList().size();
            if(auditionCount>0){
                Long auditionCountAt = this.getEnrollInfoCount(orderApply.getId(),2);
                Double dealNum = 1.0/auditionCount;
                Integer i = 0;
                Integer type = 2;
                for (Long id:orderApplyInfo.getAuditionList()){
                    if((i+auditionCountAt)<2){
                        Long teamId =  iEnrollTeamMemberService.getTeamIdForteacherId(id);
                        addEnrollInfoType(id,teamId,orderDetail.getSubjectsId(),orderApply.getStudentId(),orderApply.getId(),orderApply.getSchoolId(),dealNum,auditionMoney,auditionCount,orderApply.getHandleDate(),type);
                    }
                    i++;
                }
                this.updateEnrollDeal(orderApply.getId(),2);
            }
        }

        if(orderApplyInfo.getBargainList()!=null){
            //成交:3
            Integer bargainCount = orderApplyInfo.getBargainList().size();
            if(bargainCount>0){
                Long bargainCountAt = this.getEnrollInfoCount(orderApply.getId(),3);
                Double dealNum = 1.0/bargainCount;
                Integer i = 0;
                Integer type = 3;
                for (Long id:orderApplyInfo.getBargainList()){
                    if((i+bargainCountAt)<2){
                        Long teamId =  iEnrollTeamMemberService.getTeamIdForteacherId(id);
                        addEnrollInfoType(id,teamId,orderDetail.getSubjectsId(),orderApply.getStudentId(),orderApply.getId(),orderApply.getSchoolId(),dealNum,bargainMoney,bargainCount,orderApply.getHandleDate(),type);
                    }
                    i++;
                }
                this.updateEnrollDeal(orderApply.getId(),3);
            }
        }
        return true;
    }

    /**
     * 按类型添加
     * @param teacherId
     * @param teamId
     * @param subjectsId
     * @param studentId
     * @param orderId
     * @param schoolId
     * @param dealNum
     * @param inviteMoney
     * @param count
     * @param handleDate
     * @param type
     * @return
     */
    private boolean addEnrollInfoType(Long teacherId,Long teamId,Long subjectsId,Long studentId,Long orderId,Long schoolId,Double dealNum,BigDecimal inviteMoney,Integer count,LocalDate handleDate,Integer type){
        EnrollInfo enrollInfo = new EnrollInfo();
        enrollInfo.setTeacherId(teacherId);
        enrollInfo.setSubjectsId(subjectsId);
        enrollInfo.setStudentId(studentId);
        enrollInfo.setTeamId(teamId);
        enrollInfo.setOrderId(orderId);
        enrollInfo.setSchoolId(schoolId);
        enrollInfo.setDealNum(dealNum);
        enrollInfo.setPushMoney(inviteMoney.divide(new BigDecimal(count),BigDecimal.ROUND_HALF_UP));
        enrollInfo.setAddDate(handleDate);//与订单经办日期同步
        enrollInfo.setType(type);
        enrollInfoMapper.insert(enrollInfo);
        return true;
    }

    /**
     * 修改数量与提成
     * @param orderId
     * @param type
     * @return
     */
    private boolean updateEnrollDeal(Long orderId,Integer type){
        BigDecimal inviteMoney = new BigDecimal(120);
        BigDecimal auditionMoney = new BigDecimal(40);
        BigDecimal bargainMoney = new BigDecimal(40);

        BigDecimal pushMonnyBase;
        if(type.equals(1)){
            pushMonnyBase = inviteMoney;
        }else {
            pushMonnyBase = auditionMoney;
        }

        List<EnrollInfo> enrollInfoList = this.getEnrollInfoList(orderId,type);
        Double dealNum = 1.0/enrollInfoList.size();
        BigDecimal pushMonny;
        for (EnrollInfo enrollInfo:enrollInfoList){
            enrollInfo.setDealNum(dealNum);
            pushMonny = pushMonnyBase.multiply(new BigDecimal(dealNum));
            enrollInfo.setPushMoney(pushMonny);
            enrollInfoMapper.updateById(enrollInfo);
        }
        return true;
    }

    private Long getEnrollInfoCount(Long orderId,Integer type){
        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.eq("order_id",orderId);
        enrollInfoQueryWrapper.eq("type",type);
        return enrollInfoMapper.selectCount(enrollInfoQueryWrapper);
    }

    private List<EnrollInfo> getEnrollInfoList(Long orderId,Integer type){
        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.eq("order_id",orderId);
        enrollInfoQueryWrapper.eq("type",type);
        return enrollInfoMapper.selectList(enrollInfoQueryWrapper);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public boolean delEnrollInfo(String id){
        EnrollInfo enrollInfo = enrollInfoMapper.selectById(id);
        if(enrollInfo!=null){
            enrollInfoMapper.deleteById(enrollInfo.getId());
            this.updateEnrollDeal(enrollInfo.getOrderId(),enrollInfo.getType());
            /*
            List<EnrollInfo> enrollInfoList = this.getEnrollInfoList(enrollInfo.getOrderId(),enrollInfo.getType());
            Double dealNum = 1.0/enrollInfoList.size();
            for (EnrollInfo enrollInfoUpdate:enrollInfoList){
                enrollInfoUpdate.setDealNum(dealNum);
                enrollInfoMapper.updateById(enrollInfoUpdate);
            }*/
        }
        return true;
    }

    @Override
    public IPage<EnrollDetail> culars(IPage<?> page, Wrapper wrapper) {
        return null;
    }

    public IPage<EnrollDetail> getParticulars(IPage<?> page, Wrapper wrapper){

        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();

        List<EnrollDetail> enrollDetailList = new ArrayList<>();
        IPage<EnrollDetail> iPage = enrollInfoMapper.getParticulars(page,wrapper);

        for (EnrollDetail enrollDetail:iPage.getRecords()){

            Student student = studentMapper.selectById(enrollDetail.getStudentId());
            if (student != null){
                enrollDetail.setStudentName(student.getName());
            }
            Subjects subjects = subjectsMapper.selectById(enrollDetail.getSubjectsId());
            if(subjects!=null){
                enrollDetail.setSubjectsName(subjects.getName());
            }

            Organization organization = organizationMapper.selectById(enrollDetail.getSchoolId());
            if (organization!=null){
                enrollDetail.setSchoolName(organization.getName());
            }

            /**
             * 邀约人
             */
            List<String> inviteNameList = this.getEnrollTeacher(enrollDetail.getOrderId(),1);
            /**
             * 试听人
             */
            List<String> auditionNameList = this.getEnrollTeacher(enrollDetail.getOrderId(),2);
            /**
             * 成交人
             */
            List<String> bargainNameList = this.getEnrollTeacher(enrollDetail.getOrderId(),3);

            enrollDetail.setInviteNames(String.join(",",inviteNameList));
            enrollDetail.setAuditionNames(String.join(",",auditionNameList));
            enrollDetail.setBargainNames(String.join(",",bargainNameList));
        }

        return iPage;
    }

    @Override
    public List<String> getEnrollTeacher(Long orderId,Integer type) {

        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.eq("order_id",orderId);
        //enrollInfoQueryWrapper.eq("order_id",incomeDayReport.getOrderId());

        List<String> teacherList = new ArrayList<>();

        List<EnrollInfo> enrollInfoList = enrollInfoMapper.selectList(enrollInfoQueryWrapper);
        for (EnrollInfo enrollInfo:enrollInfoList){
            if (enrollInfo.getType().equals(type)){
                Staff staff = staffMapper.selectById(enrollInfo.getTeacherId());
                if (staff!=null){
                    teacherList.add(staff.getName());
                }
            }
        }
        return teacherList;
    }


    /**
     * 更新是否上过两次课
     * @return
     */
    @Override
    public boolean updateIsTrue(){
        Quarter quarterNow = iQuarterService.getNowQuarter();
        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        enrollInfoQueryWrapper.ge("add_date","2024-08-04");
        //enrollInfoQueryWrapper.eq("year_part",quarterNow.getYearPart());
        //enrollInfoQueryWrapper.eq("quarter_num",quarterNow.getNum());
        enrollInfoQueryWrapper.eq("is_true",0);
        enrollInfoQueryWrapper.eq("is_return",0);
        enrollInfoQueryWrapper.groupBy("order_id");
        List<EnrollInfo> enrollInfoList = enrollInfoMapper.getEnrollInfoList(enrollInfoQueryWrapper);
        for (EnrollInfo enrollInfo:enrollInfoList){
            this.updateEnrollIsTrue(enrollInfo,quarterNow.getYearPart(),quarterNow.getNum());
        }
        return true;
    }

    @Transactional
    public void updateEnrollIsTrue(EnrollInfo enrollInfo,Integer yearPart,Integer quarterNum){
        try {
            Integer count = iRecordCourseService.getRecordCountArrive(yearPart,quarterNum,enrollInfo.getStudentId(),enrollInfo.getSubjectsId());
            LocalDateTime nowDateTime = LocalDateTime.now().withNano(0);
            if (count>=2){
                UpdateWrapper<EnrollInfo> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("order_id",enrollInfo.getOrderId());
                updateWrapper.eq("is_true",0);
                updateWrapper.eq("is_return",0);
                updateWrapper.set("is_true",1);
                updateWrapper.set("true_date_time",nowDateTime);
                this.update(updateWrapper);

                List<EnrollGrantCount> enrollGrantCountList =  recordCourseMapper.getEnrollGrantCount(yearPart,quarterNum,enrollInfo.getSubjectsId(),enrollInfo.getStudentId(),1);
                if (enrollGrantCountList.size() > 0){
                    //先删除，因为会存在已发放状态因些不能删除
                    //QueryWrapper<EnrollInfoGrantSchool> enrollInfoGrantSchoolQueryWrapper = new QueryWrapper<>();
                    //enrollInfoGrantSchoolQueryWrapper.eq("order_id",enrollInfo.getOrderId());
                    //enrollInfoGrantSchoolQueryWrapper.eq("order_id",enrollInfo.getOrderId());
                    //iEnrollInfoGrantSchoolService.remove(enrollInfoGrantSchoolQueryWrapper);
                }
                BigDecimal baseNum = new BigDecimal(1);
                BigDecimal countNum = new BigDecimal(enrollGrantCountList.size());
                BigDecimal grantNum = baseNum.divide(countNum,1,BigDecimal.ROUND_HALF_UP);
                List<Long> schoolIdList = new ArrayList<>();
                for (EnrollGrantCount enrollGrantCount:enrollGrantCountList){
                    QueryWrapper<EnrollInfoGrantSchool> enrollInfoGrantSchoolQueryWrapper = new QueryWrapper<>();
                    enrollInfoGrantSchoolQueryWrapper.eq("order_id",enrollInfo.getOrderId());
                    enrollInfoGrantSchoolQueryWrapper.eq("school_id",enrollGrantCount.getSchoolId());
                    enrollInfoGrantSchoolQueryWrapper.last("limit 1");
                    EnrollInfoGrantSchool enrollInfoGrantSchool = iEnrollInfoGrantSchoolService.getOne(enrollInfoGrantSchoolQueryWrapper);
                    if (enrollInfoGrantSchool !=null){
                        enrollInfoGrantSchool.setGrantNum(grantNum);
                        iEnrollInfoGrantSchoolService.updateById(enrollInfoGrantSchool);
                    }else {
                        EnrollInfoGrantSchool enrollInfoGrantSchoolAdd = new EnrollInfoGrantSchool();
                        enrollInfoGrantSchoolAdd.setSchoolId(enrollGrantCount.getSchoolId());
                        enrollInfoGrantSchoolAdd.setOrderId(enrollInfo.getOrderId());
                        enrollInfoGrantSchoolAdd.setGrantNum(grantNum);
                        iEnrollInfoGrantSchoolService.save(enrollInfoGrantSchoolAdd);
                    }
                    schoolIdList.add(enrollGrantCount.getSchoolId());
                }
                if (schoolIdList.size()>0){
                    QueryWrapper<EnrollInfoGrantSchool> enrollInfoGrantSchoolQueryWrapper = new QueryWrapper<>();
                    enrollInfoGrantSchoolQueryWrapper.eq("order_id",enrollInfo.getOrderId());
                    enrollInfoGrantSchoolQueryWrapper.notIn("school_id",schoolIdList);
                    iEnrollInfoGrantSchoolService.remove(enrollInfoGrantSchoolQueryWrapper);
                }
            }
        }catch (Exception e){
            System.out.println("错误"+e.getMessage());
        }
    }


    @Override
    public void batchAddEnrollGrant(){
        Quarter quarterNow = iQuarterService.getNowQuarter();
        QueryWrapper<EnrollInfo> enrollInfoQueryWrapper = new QueryWrapper<>();
        //enrollInfoQueryWrapper.eq("year_part",quarterNow.getYearPart());
        //enrollInfoQueryWrapper.eq("quarter_num",quarterNow.getNum());
        //enrollInfoQueryWrapper.eq("is_true",1);
        //enrollInfoQueryWrapper.eq("is_return",0);
        enrollInfoQueryWrapper.groupBy("order_id");
        List<EnrollInfo> enrollInfoList = enrollInfoMapper.getEnrollInfoList(enrollInfoQueryWrapper);
        for (EnrollInfo enrollInfo:enrollInfoList){
            this.addEnrollGrade(enrollInfo,quarterNow.getYearPart(),quarterNow.getNum());
        }
    }

    public void addEnrollGrade(EnrollInfo enrollInfo,Integer yearPart,Integer quarterNum){
        try {
            List<EnrollGrantCount> enrollGrantCountList =  recordCourseMapper.getEnrollGrantCount(yearPart,quarterNum,enrollInfo.getSubjectsId(),enrollInfo.getStudentId(),1);
            if (enrollGrantCountList.size() >0){
                //先删除
                //QueryWrapper<EnrollInfoGrantSchool> enrollInfoGrantSchoolQueryWrapper = new QueryWrapper<>();
                //enrollInfoGrantSchoolQueryWrapper.eq("order_id",enrollInfo.getOrderId());
                //iEnrollInfoGrantSchoolService.remove(enrollInfoGrantSchoolQueryWrapper);

                BigDecimal baseNum = new BigDecimal(1);
                BigDecimal countNum = new BigDecimal(enrollGrantCountList.size());
                BigDecimal grantNum = baseNum.divide(countNum,1,BigDecimal.ROUND_HALF_UP);
                List<Long> schoolIdList = new ArrayList<>();
                for (EnrollGrantCount enrollGrantCount:enrollGrantCountList){
                    QueryWrapper<EnrollInfoGrantSchool> enrollInfoGrantSchoolQueryWrapper = new QueryWrapper<>();
                    enrollInfoGrantSchoolQueryWrapper.eq("order_id",enrollInfo.getOrderId());
                    enrollInfoGrantSchoolQueryWrapper.eq("school_id",enrollGrantCount.getSchoolId());
                    enrollInfoGrantSchoolQueryWrapper.last("limit 1");
                    EnrollInfoGrantSchool enrollInfoGrantSchool = iEnrollInfoGrantSchoolService.getOne(enrollInfoGrantSchoolQueryWrapper);
                    if (enrollInfoGrantSchool !=null){
                        enrollInfoGrantSchool.setGrantNum(grantNum);
                        iEnrollInfoGrantSchoolService.updateById(enrollInfoGrantSchool);
                    }else {
                        EnrollInfoGrantSchool enrollInfoGrantSchoolAdd = new EnrollInfoGrantSchool();
                        enrollInfoGrantSchoolAdd.setSchoolId(enrollGrantCount.getSchoolId());
                        enrollInfoGrantSchoolAdd.setOrderId(enrollInfo.getOrderId());
                        enrollInfoGrantSchoolAdd.setGrantNum(grantNum);
                        enrollInfoGrantSchoolAdd.setSubjectsId(enrollInfo.getSubjectsId());
                        enrollInfoGrantSchoolAdd.setStudentId(enrollInfo.getStudentId());
                        iEnrollInfoGrantSchoolService.save(enrollInfoGrantSchoolAdd);
                    }
                    schoolIdList.add(enrollGrantCount.getSchoolId());
                }
                if (schoolIdList.size()>0){
                    QueryWrapper<EnrollInfoGrantSchool> enrollInfoGrantSchoolQueryWrapper = new QueryWrapper<>();
                    enrollInfoGrantSchoolQueryWrapper.eq("order_id",enrollInfo.getOrderId());
                    enrollInfoGrantSchoolQueryWrapper.notIn("school_id",schoolIdList);
                    iEnrollInfoGrantSchoolService.remove(enrollInfoGrantSchoolQueryWrapper);
                }
            }else {
                EnrollInfoGrantSchool enrollInfoGrantSchoolAdd = new EnrollInfoGrantSchool();
                enrollInfoGrantSchoolAdd.setSchoolId(enrollInfo.getSchoolId());
                enrollInfoGrantSchoolAdd.setOrderId(enrollInfo.getOrderId());
                enrollInfoGrantSchoolAdd.setGrantNum(new BigDecimal(1));
                enrollInfoGrantSchoolAdd.setSubjectsId(enrollInfo.getSubjectsId());
                enrollInfoGrantSchoolAdd.setStudentId(enrollInfo.getStudentId());
                iEnrollInfoGrantSchoolService.save(enrollInfoGrantSchoolAdd);
            }
        }catch (Exception e){

        }
    }
}
